package com.linkoog.devtools.icon_viewer.core;

import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ImageLoader;
import com.intellij.util.RetinaImage;

import java.awt.*;

public class ImageWrapper {

    private static final int SIZE = JBUIScale.scale(16);
    private static final int RETINA = JBUIScale.scale(32);

    private static final float AT1X = 16.0f;
    private static final float AT2X = 32.0f;


    private IconType iconType;
    private Image image;
    private byte[] fileContents;
    private Boolean isSvg;

    public ImageWrapper(IconType iconType, Image image, byte[] fileContents){
        this.isSvg = IconType.SVG.equals(iconType);
        this.iconType = iconType;
        this.fileContents = fileContents;
        this.image = scaleImage(image);
    }

    public IconType getIconType() {
        return iconType;
    }

    public byte[] getFileContents() {
        return fileContents;
    }

    public Image getImage() {
        return image;
    }

    private Image scaleImage(Image image) {
        if (isSvg) return scaleSvg(image);

        int width = image.getWidth(null);
        int height = image.getHeight(null);

        if (width != height) { throw new IllegalStateException("Image should be square."); }
        if (width < 0) { throw new IllegalStateException("Width and height are unknown."); }

        if (width == SIZE) return image;
        if (width == RETINA) return RetinaImage.createFrom(image);

        float widthToScaleTo = JBUIScale.scale(AT1X);
        boolean retina = false;

        if (width >= RETINA) {
            widthToScaleTo = JBUIScale.scale(AT2X);
            retina = true;
        }
        Image scaledImage = ImageLoader.scaleImage(image, (widthToScaleTo / width));
        return retina ? RetinaImage.createFrom(scaledImage) : scaledImage;
    }

    private Image scaleSvg(Image image) {
        int width = image.getWidth(null);
        if (width == SIZE) return image;

        return ImageLoader.scaleImage(image, SIZE, SIZE);
    }


}
